package org.jash.wechat2205.utils;

import android.os.Handler;
import android.os.Looper;

import java.lang.annotation.Annotation;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import retrofit2.Call;
import retrofit2.CallAdapter;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class MyCallAdapterFactory extends CallAdapter.Factory {
    @Override
    public CallAdapter<?, ?> get(Type type, Annotation[] annotations, Retrofit retrofit) {
        return new MyCallAdapter(type);
    }
    private static class MyCallAdapter<T> implements CallAdapter<T, MyExecutor<T>> {
        private Type type;
        private Handler handler = new Handler(Looper.getMainLooper());
        public MyCallAdapter(Type type) {
            this.type = type;
        }

        @Override
        public Type responseType() {
            return ((ParameterizedType)type).getActualTypeArguments()[0];
        }

        @Override
        public MyExecutor<T> adapt(Call<T> call) {
            MyExecutor<T> executor = new MyExecutor<>();
            call.enqueue(new Callback<T>() {
                @Override
                public void onResponse(Call<T> call, Response<T> response) {
                    handler.post(() -> executor.success.accept(response.body()));
                }

                @Override
                public void onFailure(Call<T> call, Throwable throwable) {
                    handler.post(() -> executor.failure.accept(throwable));

                }
            });
            return executor;
        }


    }
}
